﻿/// <reference path="jquery-1.4.1-vsdoc.js"/>

var user = null;
var now = new Date();
var m_names = ["January", "February", "March",
                    "April", "May", "June", "July", "August", "September",
                    "October", "November", "December"];

/*
new Array("January", "February", "March",
                    "April", "May", "June", "July", "August", "September",
                    "October", "November", "December");
*/                    
function documentLoad() {

    $("#userProfile").accordion({ collapsible: true, autoHeight: false, header: "h3", clearstyle: true });
    $("#divErrorMessages").hide();
    $("#divErrorMessages").accordion({ collapsible: true, autoHeight: false, header: "h3" });
   /*
    $("#divAvatar").dialog({
        autoOpen: false,
        closeOnEscape: true,
        draggable: false,
        height: 'auto',
        width: 'auto',
        title: 'Change Avatar',
        modal: false,
        resizable: false
    });
    $("#btnAvatarCancel").click(function (e) {
        $("#divAvatar").dialog('close');
    });

    $("#btnChangeAvatar").click(function () {
        $("#divAvatar").dialog('open');
    });
    */

    $("#Create").click(function () {
        RegisterUser();
    });

    $("#Cancel").click(function () {
        Close();
    });

    /* Add the date picker to the date of birth field */
    $("#txtDateOfBirth").datepicker({ onSelect: function (date) { },
        dateFormat: "MM dd, yy",
        yearRange: (now.getYear() - 80) + ":" + now.getYear(),
        showOn: "both",
        changeMonth: true, changeYear: true
    });
    /* Disable direct entry into the textbox */
    $("#txtDateOfBirth").attr('readonly', true);
    $('#ui-datepicker-div').css('z-index', 2005);

    /* attach event handler to the selected event */
    $("#drpCountry").change(function () {
        LookupStates();
    });

    /* Upload control */
    /*
    var button = $('#txtAvatarBrowse'), interval;
    var upload = new AjaxUpload(button, {
        action: fileUploadUrl,
        name: 'avatar',
        onSubmit: function (file, ext) {
            //checking file extension
            if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
                // extension is not allowed
                alert('Error: invalid file extension');
                // cancel upload
                return false;
            }

            // change button text, when user selects file			
            button.text('Uploading');
            // provide the userguid as a querystring
            this.setData({ 'UserGuid': $("#txtUserId").val() });

            // If you want to allow uploading only 1 file at time,
            // you can disable upload button
            this.disable();

            // Uploading -> Uploading. -> Uploading..
            interval = window.setInterval(function () {
                var text = button.text();
                if (text.length < 13) {
                    button.text(text + '.');
                } else {
                    button.text('Uploading');
                }
            }, 200);
        },
        onComplete: function (file, response) {
            button.text('Upload');
            window.clearInterval(interval);

            // enable upload button
            this.enable();
            // add file to the picturebox
            var extension = (file.substr(file.indexOf(".") + 1, file.length - file.indexOf(".") - 1));
            $("#divAvatar").dialog('close');
            window.location.reload(true);
        }
    });
    */
    // add preset images
    /*
    $("#imgPerson1").attr("src", preSetImagesUrl + "Person1.png");
    $("#imgPerson2").attr("src", preSetImagesUrl + "Person2.png");
    $("#imgPerson3").attr("src", preSetImagesUrl + "Person3.png");
    $("#imgPerson4").attr("src", preSetImagesUrl + "Person4.png");

    $(".avatarImages").mouseenter(function (e) {
        $(e.currentTarget).addClass("avatarImages-Highlighted");
    });

    $(".avatarImages").mouseleave(function (e) {
        $(e.currentTarget).removeClass("avatarImages-Highlighted");
    });
    */
    LookUpCountries();  
}

function ShowConfirmation() {
    var email = $.trim($("#txtEmail").val());
    $("#confirmationEmail").text(email);

    $("#RegisterSuccess").dialog({
        autoOpen: true,
        closeOnEscape: false,
        draggable: false,
        height: 'auto',
        width: 'auto',
        title: 'Account Created - Please Activate',
        modal: true,
        resizable: false,
        buttons: { "Ok": function () { $(this).dialog("close"); window.location = "/"; } }
    });

    /* Remove the X in the dialog box */
    $('.ui-dialog-titlebar-close').remove();
}

function RegisterUser() {
    if (ValidateUserDetails()) {
        var user = {
            "basicInfo": { "Username": $("#txtUsername").val(),
                "Firstname": $("#txtFirstname").val(),
                "Lastname": $("#txtLastname").val(),
                "Email": $("#txtEmail").val(),
                "Password": $("#Password1").val()
            },
            "personalInfo": {
                "Nickname": $("#txtNickname").val(),
                "Sex": $("#drpSex").val(),
                "Mobile": $("#txtMobile").val(),
                "DateOfBirth": $("#txtDateOfBirth")[0].value,
                /* "AvatarUrl": htmlEncode($("#picAvatar").attr("src")), */
                "Phone": $("#txtPhone").val(),
                "State": $("#drpState").val(),
                "Country": $("#drpCountry").val(),
                "Postcode": $("#txtPostcode").val(),
                "Comment": $("#txtNotes").val()
            },
            "mailSettings": {
                "AcceptAdvertisingEmail": eval($("#chkAdvertisingEmail").is(":checked")),
                "AcceptCommunityEmail": eval($("#chkCommunityEmail").is(":checked"))
            }
        };
        var userObj = "user=" + JSON.stringify(user);
        CallWebService(accountRegisterUserUrl, userObj,
                function (result) {
                    var response = JSON.parse(result.d);
                    if (response.IsSuccess == false) {
                        //ShowErrorMessage(response);
                        var errorHTML = "<table>";
                        $.each(response.Payload, function () {
                            errorHTML += "<tr>";
                            errorHTML += "<td style='width:100%'>" + "<span><strong>" + this.Message + "</strong></span></td>";
                            errorHTML += "</tr>";
                        });
                        errorHTML += "</table>";
                        $("#divErrors").html(errorHTML);
                        $("#divErrorMessages").show();
                        alert("There were registration errors. Press OK to fix.");
                    } else {
                        ShowConfirmation();
                    }
                });
    }
}

function Close() {
    window.location.href = "/";
}

function LookUpCountries() {
    // clear the dropdowns
    $("#drpCountry").empty();
    CallWebService(lookupCountriesUrl, "",
        function (result) {
            var response = JSON.parse(result.d);
            if (response.IsSuccess == true) {
                var countries = response.Payload;
                for (var i = 0; i < countries.length; i++) {
                    $('#drpCountry').append("<option value='" + countries[i].ID + "'>" + countries[i].Name + "</option>")
                }
                LookupStates();
            }
        });
}

function LookupStates() {
    $("#drpState").empty();
    var countryId = { "countryId": $("#drpCountry").val() };
    CallWebService(lookupStatesUrl, countryId,
                    function (result) {
                        var response = JSON.parse(result.d);
                        if (response.IsSuccess == true) {
                            var states = response.Payload;
                            for (var i = 0; i < states.length; i++) {
                                $('#drpState').append("<option value='" + states[i].ID + "'>" + states[i].Name + "</option>")
                            }
                        }
                    });
}


/* Validate entered field on the form, returns false for validation errors */
function ValidateUserDetails() {
    var ret = false;
    var errors = new Array();
    if ($.trim($("#txtUsername").val()) == "") {
        errors[errors.length] = { "Control": "txtUsername", "Message": "Username cannot be empty." };
    }
    if ( $.trim($("#Password1").val()) != $.trim($("#Password2").val())  && $.trim($("#Password1").val())!="" ) {
        errors[errors.length] = { "Control": "Password1", "Message": "Passwords must match." };
    }
    if ($.trim($("#Password1").val()) == "") {
        errors[errors.length] = { "Control": "Password1", "Message": "Password cannot be empty." };
    }
    if ($.trim($("#txtFirstname").val()) == "") {
        errors[errors.length] = { "Control": "txtFirstname", "Message": "First name cannot be empty." };
    }
    if ($.trim($("#txtLastname").val()) == "") {
        errors[errors.length] = { "Control": "txtLastname", "Message": "Last name cannot be empty." };
    }
    if ($.trim($("#txtEmail").val()) == "") {
        errors[errors.length] = { "Control": "txtEmail", "Message": "Email cannot be empty." };
    }
    if ( !eval($("#chkTerms").is(":checked")) ) {
        errors[errors.length] = { "Control": "chkTerms", "Message": "You must accept the terms and conditions." };
    }
    var errorHTML = "";
    if (errors.length > 0) {
        errorHTML = "<table style='width:100%'>";
    }
    $.each(errors, function () {
        errorHTML += "<tr>";
        errorHTML += "<td class='ErrorTD' style='width:100%' onclick=ShowErrorDetails('" + this.Control + "');>"
                    + "<span><strong>" + this.Message + "</strong></span></td>";
        errorHTML += "</tr>";
    });
    if (errors.length > 0) {
        alert("There were registration errors. Press OK to fix.");
        $("#divErrorMessages").show();
        errorHTML += "</table>";
        ret = false;
    }
    else {
        ret = true;
        $("#divErrorMessages").hide();
    }
    $("#divErrors").html(errorHTML);
    /*
    $(".ErrorTD").mouseenter(function () {
        $(".ErrorTD").removeClass('Highlight');
        $(this).addClass('Highlight');
    });
    $(".ErrorTD").mouseleave(function () {
        $(this).removeClass('Highlight');
    });
    */
    return ret;
}

function ShowErrorDetails(Control) {
    $('#userProfile').accordion('activate', 0);
    $("#" + Control).focus();
}